#include "shaders/Dielectric.hpp"
#include "samplers/SamplerInstance.hpp"

#include "Onb.hpp"

namespace SimplePathTracer
{
    Dielectric::Dielectric(Material& material, vector<Texture>& textures)
        : Shader(material, textures)
    {
        auto _ior = material.getProperty<Property::Wrapper::FloatType>("ior");
        if (_ior) ior = (*_ior).value;
        else ior = 1.f;
        auto _absorbed = material.getProperty<Property::Wrapper::RGBType>("absorbed");
        if (_absorbed) absorbed = (*_absorbed).value;
        else absorbed = {1, 1, 1};
    }
    Scattered Dielectric::shade(const Ray& ray, const Vec3& hitPoint, const Vec3& normal) const {
        Vec3 origin = hitPoint;

        Vec3 direction = {0, 0, 0};
        float d = glm::dot(normal, ray.direction);
        float _ior = d > 0 ? ior : 1.f / ior;
        float k = 1.0 - _ior * _ior * (1.0 - d * d);
        if (k >= 0.f)
            direction = _ior * ray.direction - (_ior * d + sqrt(k)) * normal;

        auto attenuation = absorbed / PI;

        float pdf = 1 / (2 * PI);

        Ray out(origin, direction);

        return {
            Ray{out.at(0.1f), direction},
            attenuation,
            Vec3{0},
            pdf
        };
    }
}